<?php
/*
 * @Date: 2021-08-23 09:30:36
 * @LastEditTime: 2021-12-16 14:56:57
 */

declare(strict_types=1);

namespace catchAdmin\monitor\command;

use catchAdmin\delivery\common\DeliveryUspsCommon;
use catchAdmin\warehouse\model\Warehouses;
use catchAdmin\order\model\OrderDeliver;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use Carbon\Carbon;


class UspsTrackingCommand extends Command
{
    protected $pid;

    protected function configure()
    {
        // 指令配置
        $this->setName('catch:UspsTracking')
            ->setDescription('get usps tracking info');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('uspsTracking Error Line:' . $e->getLine());
            Log::error('uspsTracking Error Code:' . $e->getCode());
            Log::error('uspsTracking Error Message:' . $e->getMessage());
            echo $e->getMessage() . "\r\n";
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 执行 command
     *
     * @time 2021年03月02日
     * @return void
     */
    protected function executeCommand()
    {
        $orders = OrderDeliver::whereBetween('delivery_state', '2,4')
            ->field('shipping_code, en_id')
            ->whereLike('shipping_name', 'USPS')
            ->where('logistics_type', 1) // 发货物流类型 0-未设置 1-自有物流 2-它有物流
            ->where('delivery_process_status', 2) // // 是否打印面单 1-未打印 2-打印
            ->where('created_at', '>', 1626969600)
            ->order('id', 'desc')
            ->select();
        $usps = new DeliveryUspsCommon([]);

        foreach ($orders as $order) {
            echo 'CODE:' .$order->shipping_code . "\r\n";
            $companyWarehouse  = new Warehouses;
            $usps_json = $companyWarehouse->where(['id' => $order->en_id])->value('usps_json');

            if(!$usps_json) {
                Log::error('仓库设置usps账户不存在' . $order->en_id);
                continue;
            }
            $obj = json_decode($usps_json, true);
            $userId = $obj['WebtoolsID'];

            $shippingCode = $order->shipping_code;

            $res = $usps->tracking([$shippingCode], $userId);
            if (!is_array($res)) {
                Log::error('usps物流信息不存在：'. json_encode($res));
                continue;
            }else{
                if($res && isset($res['TrackDetail'])) {
                    $oldXmlObj = $res['TrackDetail'];
                    $result = $oldXmlObj;
                    if (is_array($result)) {
                        $code = $result[0];
                    }else{
                        $code = $result;
                    }
                    $EventTime = !empty($code['EventTime'])>0 ? $code['EventTime'] : '';
                }else{
                    $oldXmlObj = $res['TrackSummary'];
                    $result = $oldXmlObj;
                    $code = $result;
                    $EventTime = '';
                }
                if (strpos($code['Event'], 'Out for Delivery') !== false) {
                    $delivery_state = 5;
                } else {
                    $delivery_state = 4;
                }
                // $dateTime = new Carbon($code['EventDate'] . ' ' . $EventTime);
                $dateTime = Carbon::parse($code['EventDate'] . ' ' . $EventTime)->toDateTimeString();
                
                $deliver_day = strtotime($dateTime);

                OrderDeliver::update(
                    [
                    'delivery_state' => $delivery_state,
                    'tracking_info' => json_encode($res),
                    'deliver_day' => $deliver_day,
                    'updated_at' => time()
                ],
                    ['shipping_code' => $order->shipping_code]
                );
            }
        }
    }
}
